package com.member.mp.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.mp.config.WxMaConfiguration;
import com.member.mp.config.WxMaProperties;
import com.member.mp.utils.GenerateQR;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.SysBizActivity;
import com.member.shop.domain.SysBizActivityEnroll;
import com.member.shop.domain.SysBizMarketPage;
import com.member.shop.domain.SysBizUser;
import com.member.shop.dto.SysBizMarketPageDto;
import com.member.shop.dto.SysBizSaleActivityDto;
import com.member.shop.service.ISysBizActivityEnrollService;
import com.member.shop.service.ISysBizActivityService;
import com.member.shop.service.ISysBizMarketPageService;
import com.member.shop.service.ISysBizUserService;
import com.member.shop.vo.ActivityEnrollDto;
import com.member.shop.vo.ActivityOrderDetailVo;
import com.member.shop.vo.FieldData;
import com.member.shop.vo.PayVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 【活动】控制器
 *
 * @author wangxin
 * @version 1.0
 * @date Mon Jul 03 22:06:51 CST 2024
 **/
@Slf4j
@Api(value = "营销活动接口", tags = {"营销活动接口"})
@RestController
@RequestMapping("/wx/activity")
public class ActivityController extends SupperController {

    @Resource
    private ISysBizActivityService sysBizActivityService;
    @Resource
    private ISysBizActivityEnrollService sysBizActivityEnrollService;
    @Resource
    private ISysBizUserService sysBizUserService;

    /**
     * 查询全部活动（带分页）
     *
     * @return 活动列表
     */
    // @GetMapping("/queryActivityAll")
    public R<PageResult<SysBizActivity>> queryActivityAll() {
        startPage();
        Long tenantId = getTenantId();
        // 只要线上活动
        List<SysBizActivity> activityList = sysBizActivityService.queryActivityAll(null, 0, tenantId);
        TableDataInfo dataTable = getDataTable(activityList);
        List<?> rows = dataTable.getRows();
        ArrayList<SysBizActivity> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizActivity sysBizActivity = (SysBizActivity) row;
            SysBizActivity target = new SysBizActivity();
            BeanUtils.copyProperties(sysBizActivity, target);
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }


    @Autowired
    private ISysBizMarketPageService marketPageService;

//    /**
//     * 查询营销页详情 (0:商品营销 1 秒杀,专题接口)
//     *
//     * @return 活动详情
//     */
//    @GetMapping("/queryMarketPageByRegion/{region}")
//    public R<SysBizMarketPage> queryMarketPageByRegion(@PathVariable Integer region) {
//        SysBizMarketPage marketPage = marketPageService.queryMarketPageByRegion(region, getTenantId());
//        return R.ok(marketPage);
//    }

//    /**
//     * 查询商品所参加的专题(返回一个专题)
//     *
//     * @return 商品id
//     */
//    @GetMapping("/queryMarketPageByGoodsId/{id}")
//    public R<SysBizMarketPage> queryMarketPageByGoodsId(@PathVariable Long id) {
//        SysBizMarketPage sysBizMarketPage = marketPageService.queryMarketPageByGoodsId(id, getTenantId());
//        return R.ok(sysBizMarketPage);
//    }



    /**
     * 获取营销活动
     *
     * @return 营销活动id
     */
    @GetMapping("/queryMarketPage/{id}")
    public R<SysBizMarketPageDto> queryMarketPageByGoodsId(@PathVariable Long id) {
        Long tenantId = getTenantId();
        Long userId = getUserId();
//        Long tenantId = 1L;
//        Long userId = 1063679937077667L;

        SysBizMarketPageDto sysBizMarketPage = marketPageService.queryMarketPage(id, tenantId,userId);
        return R.ok(sysBizMarketPage);
    }



    /**
     * 首页秒杀活动专区
     *
     * @return 营销活动id
     */
    @GetMapping("/saleActivity")
    public R<SysBizSaleActivityDto> saleActivity() {
        Long tenantId = getTenantId();
        SysBizSaleActivityDto sysBizMarketPage = marketPageService.saleActivity(tenantId);
        return R.ok(sysBizMarketPage);
    }



    /**
     * 查询活动详情
     *
     * @return 活动详情
     */
    //@GetMapping("/queryActivityById/{id}")
    public R<SysBizActivity> queryActivityById(@PathVariable Long id) {
        SysBizActivity sysBizActivity = sysBizActivityService.queryActivityById(id, getUserId());
        return R.ok(sysBizActivity);
    }

    private static final String CHINA_PHONE_PATTERN = "^1[3-9]\\d{9}$";

    @Resource
    private WxMaProperties wxMaProperties;

    /**
     * 生成活动预订单
     *
     * @param activityEnrollDto 参数
     * @return 活动价格
     */
    //@PostMapping("/perActivityOrder")
    public R<ActivityOrderDetailVo> perActivityOrder(@RequestBody @Validated ActivityEnrollDto activityEnrollDto) throws WxErrorException {
        SysBizUser byId = sysBizUserService.getById(getUserId());
        if (byId.getUserRole() == 0) {
            return R.notRegister("请先注册会员");
        }
        Long tenantId = getTenantId();
        if (StringUtils.isBlank(byId.getOpenId()) && StringUtils.isNotBlank(activityEnrollDto.getCode())) {
            String appid = wxMaProperties.getConfigs().get(0).getAppid();
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(activityEnrollDto.getCode());
            byId.setOpenId(session.getOpenid());
            sysBizUserService.updateById(byId);
        }
        if (StringUtils.isNotBlank(activityEnrollDto.getFieldList())) {
            List<FieldData> fieldDataList = JSON.parseArray(activityEnrollDto.getFieldList(), FieldData.class);
            if (!CollectionUtils.isEmpty(fieldDataList)) {
                for (FieldData fieldData : fieldDataList) {
                    if ("身份证号".equals(fieldData.getName())) {
                        if (fieldData.getValue() == null || (fieldData.getValue().length() != 18)) {
                            return R.fail("身份证号码不合法");
                        }
                        // 省略15位身份证的校验逻辑
                        if (!fieldData.getValue().matches("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}([0-9Xx])$")) {
                            return R.fail("身份证号码不合法");
                        }

                        // 校验码验证
                        char[] idCardArray = fieldData.getValue().toCharArray();
                        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                        char[] checkCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
                        int sum = 0;
                        for (int i = 0; i < idCardArray.length - 1; i++) {
                            sum += (idCardArray[i] - '0') * weights[i];
                        }
                        char lastChar = checkCode[sum % 11];
                        if (lastChar != idCardArray[17]) {
                            return R.fail("身份证号码不合法");
                        }
                    }
                    if ("电话".equals(fieldData.getName())) {
                        if (fieldData.getValue() == null || fieldData.getValue().isEmpty()) {
                            return R.fail("手机号码不合法");
                        }
                        if (!fieldData.getValue().matches(CHINA_PHONE_PATTERN)) {
                            return R.fail("手机号码不合法");
                        }
                    }
                }
            }
        }
        ActivityOrderDetailVo activityOrderDetailVo = new ActivityOrderDetailVo();
        LambdaQueryWrapper<SysBizActivityEnroll> sysBizActivityEnrollLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getUserId, getUserId());
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getPayStatus, 0);
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getTenantId, tenantId);

        sysBizActivityEnrollLambdaQueryWrapper.gt(SysBizActivityEnroll::getPaymentEndTime, DateUtils.getNowDate());
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getActivityId, activityEnrollDto.getActivityId());
        List<SysBizActivityEnroll> sysBizActivityEnrolls = sysBizActivityEnrollService.selectSysBizActivityEnrollList(sysBizActivityEnrollLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(sysBizActivityEnrolls)) {
            SysBizActivityEnroll sysBizActivityEnroll = sysBizActivityEnrolls.get(0);
//            sysBizActivityEnroll.setName(activityEnrollDto.getName());
//            sysBizActivityEnroll.setPhone(activityEnrollDto.getPhone());
//            sysBizActivityEnroll.setEnrollUserType(activityEnrollDto.getEnrollUserType());
            sysBizActivityEnroll.setPaymentEndTime(DateUtils.addMinutes(DateUtils.getNowDate(), 15));
            sysBizActivityEnroll.setInfo(activityEnrollDto.getFieldList());
            // 2024 0327 新增四个报名固定字段
//            sysBizActivityEnroll.setIdCard(activityEnrollDto.getIdCard());
//            sysBizActivityEnroll.setDivideGroup(activityEnrollDto.getDivideGroup());
//            sysBizActivityEnroll.setReference(activityEnrollDto.getReference());
//            sysBizActivityEnroll.setRemark(activityEnrollDto.getRemark());
            sysBizActivityEnrollService.updateById(sysBizActivityEnroll);
            BeanUtils.copyProperties(sysBizActivityEnroll, activityOrderDetailVo);
            return R.ok(activityOrderDetailVo);
        }
        SysBizUser loginUser = getLoginUser();
        SysBizActivityEnroll sysBizActivityEnroll = new SysBizActivityEnroll();

        sysBizActivityEnroll.setTenantId(tenantId);
        // 准备订单数据，判断是否有异常信息
        String preorder = sysBizActivityService.preActivityOrder(loginUser.getId(), activityOrderDetailVo, activityEnrollDto, sysBizActivityEnroll);
        if (StringUtils.isNotBlank(preorder)) {
            return R.fail(preorder);
        }
        // 生成核销二维码
        String code = GenerateQR.code(sysBizActivityEnroll.getId().toString());
        if (StringUtils.isBlank(code)) {
            log.error("生成核销码失败：{}", sysBizActivityEnroll.getId());
        }
        long time = DateUtils.getNowDate().getTime();
        String vCode = time + String.format("%2d", 10 + new Random().nextInt(90));
        sysBizActivityEnroll.setWriteOffCode(vCode);
        sysBizActivityEnroll.setWriteOffImage(code);
        sysBizActivityEnrollService.updateById(sysBizActivityEnroll);
        return R.ok(activityOrderDetailVo);
    }

}
